//端口
const wsPort = 9437
//通讯地址
const hostname = document.location.hostname;
//创建一个对象
const ws = new WebSocket(`ws://${hostname}:${wsPort}`)

//获取GET参数
var $_GET = (function () {
    var url = window.document.location.href.toString();
    var u = url.split("?");
    if (typeof (u[1]) == "string") {
        u = u[1].split("&");
        var get = {};
        for (var i in u) {
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
})();
console.log($_GET['key']);

//创建一个唯一标识
function getuid() {
    //如果唯一标识不存在则创建 储存本地
    if (localStorage.getItem("uid")) {
        //取出本地储存标识
        return localStorage.getItem("uid");
    } else {
        //获取当前时间戳
        var timestamp = new Date().getTime();
        //时间戳储存本地
        localStorage.setItem("uid", timestamp);
        return timestamp;
    }
}

//连接建立时触发
ws.onopen = () => {
    myVue.key = $_GET['key'];//获得密钥
    myVue.user.uid = getuid();//获取发送者标识
    myVue.user.uvisit = true;
    //进入客服页面提示.
    var data = JSON.stringify({
        "user": "support",//消息来源
        "time": myVue.GetNowTime(),//时间
        "type": "text",//消息类型
        "msg": "<p>已为您转接客服...</p>",//消息内容
        "visit": "",//消息发送对象
        "uid": myVue.user.uid,//发送者标识
        "key": myVue.key,//密钥
        "init": 'user'
    });
    ws.send(data);
}

//客户端接收服务端数据时触发
ws.onmessage = (msg) => {
    console.log('源' + msg);
    //接收数据，然后将数据展示到界面上 
    var da = JSON.parse(msg.data);
    //为用户提供客服标识
    if (myVue.user.uvisit) {
        //如果唯一标识不存在则创建 储存本地
        if (localStorage.getItem("visit")) {
            //取出本地储存标识
            myVue.user.visit = localStorage.getItem("visit");
        } else {
            if (da.info) {
                //储存客服标识到本地
                localStorage.setItem("visit", da.info.visit);
                myVue.user.visit = da.info.visit;
            } else {
                //储存客服标识到本地
                localStorage.setItem("visit", da.visit);
                myVue.user.visit = da.visit;
            }

        }
    }
    //如果信息数据存在则导入
    if (da.info) {
        console.log('历史' + da.data);
        myVue.chatData = (da.data);
        GoBottom();
    } else {
        console.log(da);
        console.log(myVue.user.uid);
        //将数据存入到页面
        myVue.chatData.push(da);
        GoBottom();
    }
}

//通信发生错误时触发
ws.onerror = (error) => {
    // console.log(error)
    console.log("未知错误连接断开...");

}

//连接关闭时触发
ws.onclose = () => {
    var data = JSON.stringify({
        "user": "support",//消息来源
        "time": myVue.GetNowTime(),//时间
        "type": "text",//消息类型
        "msg": "<p>通讯已断开...</p>",//消息内容
    });
    myVue.chatData.push(JSON.parse(data));
    GoBottom();
    console.log('通讯连接断开...')
}

var myVue = new Vue({
    el: "#app",
    data() {
        return {
            user: {
                uid: '',
                visit: '',
                key: '',
                uvisit: true,
            },
            chatData: [
            ],
        }
    },
    computed: {
        //消息时间差，超过180秒，则显示消息发送时间
        Long: function () {
            return function (index) {
                if (index > 0) {
                    var prveTime1 = this.chatData[index - 1].time.slice(0, 10);
                    var prveTime2 = this.chatData[index - 1].time.slice(15);
                    var prveTime = prveTime1 + ' ' + prveTime2

                    var nowTime1 = this.chatData[index].time.slice(0, 10);
                    var nowTime2 = this.chatData[index].time.slice(15);
                    var nowTime = nowTime1 + ' ' + nowTime2

                    var d1 = new Date(prveTime);
                    var d2 = new Date(nowTime);

                    var longTime = parseInt(d2 - d1) / 1000;

                    if (longTime > 5) {
                        return true;
                    } else {
                        return false;
                    }
                }
            };
        },
        //判断消息类型是 客服-文本
        SupportText: function () {
            return function (index) {
                if (this.chatData[index].user == "support" && this.chatData[index].type == "text") {
                    return true;
                } else {
                    return false;
                }
            }
        },
        //判断消息类型是 客服-图片
        SupportPic: function () {
            return function (index) {
                if (this.chatData[index].user == "support" && this.chatData[index].type == "pic") {
                    return true;
                } else {
                    return false;
                }
            }
        },
        //判断消息类型是 游客-文本
        VisitorText: function () {
            return function (index) {
                if (this.chatData[index].user == "visitor" && this.chatData[index].type == "text") {
                    return true;
                } else {
                    return false;
                }
            }
        },
        //判断消息类型是 游客-图片
        VisitorPic: function () {
            return function (index) {
                if (this.chatData[index].user == "visitor" && this.chatData[index].type == "pic") {
                    return true;
                } else {
                    return false;
                }
            }
        },
    },
    methods: {

        Send() {
            var inputInfo = editor.txt.html();
            if (inputInfo != "<p><br></p>") {
                var newInfo = JSON.stringify({
                    uid: this.user.uid,
                    user: "visitor",//消息来源
                    time: this.GetNowTime(),//时间
                    type: "text",//消息类型
                    msg: inputInfo,//消息内容
                    visit: this.user.visit,//消息发送到
                    uid: this.user.uid,//发送用户标识
                    key: this.key,
                });
                ws.send(newInfo);
                // this.chatData.push(newInfo);
                console.log(this.chatData);
                editor.txt.html('');    //清空输入框
                GoBottom();     //跳到最新消息
            };
        },
        GetNowTime() {
            //判断是否在前面加0
            function getNow(s) {
                return s < 10 ? '0' + s : s;
            }

            var myDate = new Date();

            var year = myDate.getFullYear();        //获取当前年
            var month = myDate.getMonth() + 1;   //获取当前月
            var date = myDate.getDate();            //获取当前日

            var str = "星期" + "日一二三四五六".charAt(new Date().getDay());

            var h = myDate.getHours();              //获取当前小时数(0-23)
            var m = myDate.getMinutes();          //获取当前分钟数(0-59)
            var s = myDate.getSeconds();

            var now = year + '/' + getNow(month) + "/" + getNow(date) + " " + str + " " + getNow(h) + ':' + getNow(m) + ":" + getNow(s);

            return now;
        }
    },
})


/**富文本编辑器 开始 */
var E = window.wangEditor
var editor = new E('#editor')
editor.customConfig.menus = [
    'emoticon', // 表情
    'image', // 插入图片
    'undo', // 撤销
    'redo' // 重复
]
editor.customConfig.pasteFilterStyle = false; // 关闭粘贴内容中的样式
editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片

editor.customConfig.customUploadImg = function (files, insert) {
    var imgSize = (files[0].size / 1024).toFixed(0); //选择的图片大小
    // console.log(imgSize);
    var imgBase64;

    if (imgSize > 500) {
        alert('图片大小超出500KB限制');
        return false;
    } else {
        var file = files[0];
        if (window.FileReader) {
            var reader = new FileReader();
            reader.readAsDataURL(file);

            //监听文件读取结束后事件    
            reader.onloadend = function (e) {
                imgBase64 = e.target.result; // 图片base64
                // console.log(imgBase64);
                var newInfo = {
                    user: "visitor",
                    time: myVue.GetNowTime(),
                    type: "pic",
                    msg: imgBase64,
                    visit: myVue.user.visit, //消息发送对象
                    uid: myVue.user.uid,//发送用户标识
                    key: myVue.key,
                };
                console.log(newInfo);
                ws.send(JSON.stringify(newInfo)); //发送
                // myVue.chatData.push(newInfo);

                myVue.GoBottom();
            };
        }
    }

    // 上传代码返回结果之后，将图片插入到编辑器中
    // insert(imgUrl);
}

// 表情面板可以有多个 tab ，因此要配置成一个数组。数组每个元素代表一个 tab 的配置
editor.customConfig.emotions = [
    {
        // tab 的标题
        title: 'emoji',
        // type -> 'emoji' / 'image'
        type: 'image',
        // content -> 数组
        content: [
            { "src": "http://www.emojidaquan.com/pics/apple/grinning-face-fb1007.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/grinning-face-with-smiling-eyes-fb1005.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/face-with-tears-of-joy-fb491.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/rolling-on-the-floor-laughing-fb1992.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/smiling-face-with-open-mouth-fb2097.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/smiling-face-with-open-mouth-and-smiling-eyes-fb2095.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/smiling-face-with-open-mouth-and-cold-sweat-fb2094.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/smiling-face-with-open-mouth-and-tightly-closed-eyes-fb2096.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/winking-face-fb2381.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/smiling-face-with-smiling-eyes-fb2099.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/face-savouring-delicious-food-fb461.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/smiling-face-with-sunglasses-fb2100.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/smiling-face-with-heart-shaped-eyes-fb2092.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/face-throwing-a-kiss-fb463.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/kissing-face-fb1165.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/kissing-face-with-smiling-eyes-fb1164.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/kissing-face-with-closed-eyes-fb1163.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/white-smiling-face-fb2360.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/slightly-smiling-face-fb2084.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/hugging-face-fb1097.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/grinning-face-with-star-eyes-fb1006.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/thinking-face-fb2213.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/face-with-one-eyebrow-raised-fb483.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/neutral-face-fb1673.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/expressionless-face-fb443.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/face-without-mouth-fb493.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/face-with-rolling-eyes-fb487.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/smirking-face-fb2101.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/persevering-face-fb1785.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/disappointed-but-relieved-face-fb377.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/face-with-open-mouth-fb486.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/zipper-mouth-face-fb2611.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/hushed-face-fb1099.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/sleepy-face-fb2075.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/tired-face-fb2234.png" },
            { "src": "http://www.emojidaquan.com/pics/apple/speak-no-evil-monkey-fb2121.png" },
        ]
    },
    {
        // tab 的标题
        title: '微博表情',
        // type -> 'emoji' / 'image'
        type: 'image',
        // content -> 数组
        content: [
            { "alt": "[微笑]", "src": "/assets/img/icon/0.png" },
            { "alt": "[可爱]", "src": "/assets/img/icon/1.png" },
            { "alt": "[太开心]", "src": "/assets/img/icon/2.png" },
            { "alt": "[鼓掌]", "src": "/assets/img/icon/3.png" },
            { "alt": "[嘻嘻]", "src": "/assets/img/icon/4.png" },
            { "alt": "[哈哈]", "src": "/assets/img/icon/5.png" },
            { "alt": "[笑cry]", "src": "/assets/img/icon/6.png" },
            { "alt": "[挤眼]", "src": "/assets/img/icon/7.png" },
            { "alt": "[馋嘴]", "src": "/assets/img/icon/8.png" },
            { "alt": "[黑线]", "src": "/assets/img/icon/9.png" },
            { "alt": "[汗]", "src": "/assets/img/icon/10.png" },
            { "alt": "[挖鼻]", "src": "/assets/img/icon/11.png" },
            { "alt": "[哼]", "src": "/assets/img/icon/12.png" },
            { "alt": "[怒]", "src": "/assets/img/icon/13.png" },
            { "alt": "[委屈]", "src": "/assets/img/icon/14.png" },
            { "alt": "[可怜]", "src": "/assets/img/icon/15.png" },
            { "alt": "[失望]", "src": "/assets/img/icon/16.png" },
            { "alt": "[悲伤]", "src": "/assets/img/icon/17.png" },
            { "alt": "[泪]", "src": "/assets/img/icon/18.png" },
            { "alt": "[允悲]", "src": "/assets/img/icon/19.png" },
            { "alt": "[害羞]", "src": "/assets/img/icon/20.png" },
            { "alt": "[污]", "src": "/assets/img/icon/21.png" },
            { "alt": "[爱你]", "src": "/assets/img/icon/22.png" },
            { "alt": "[亲亲]", "src": "/assets/img/icon/23.png" },
            { "alt": "[色]", "src": "/assets/img/icon/24.png" },
            { "alt": "[憧憬]", "src": "/assets/img/icon/25.png" },
            { "alt": "[舔屏]", "src": "/assets/img/icon/26.png" },
            { "alt": "[坏笑]", "src": "/assets/img/icon/27.png" },
            { "alt": "[阴险]", "src": "/assets/img/icon/28.png" },
            { "alt": "[笑而不语]", "src": "/assets/img/icon/29.png" },
            { "alt": "[偷笑]", "src": "/assets/img/icon/30.png" },
            { "alt": "[酷]", "src": "/assets/img/icon/31.png" },
            { "alt": "[并不简单]", "src": "/assets/img/icon/32.png" },
            { "alt": "[思考]", "src": "/assets/img/icon/33.png" },
            { "alt": "[疑问]", "src": "/assets/img/icon/34.png" },
            { "alt": "[费解]", "src": "/assets/img/icon/35.png" },
            { "alt": "[晕]", "src": "/assets/img/icon/36.png" },
            { "alt": "[衰]", "src": "/assets/img/icon/37.png" },
            { "alt": "[骷髅]", "src": "/assets/img/icon/38.png" },
            { "alt": "[嘘]", "src": "/assets/img/icon/39.png" },
            { "alt": "[闭嘴]", "src": "/assets/img/icon/40.png" },
            { "alt": "[傻眼]", "src": "/assets/img/icon/41.png" },
            { "alt": "[吃惊]", "src": "/assets/img/icon/42.png" },
            { "alt": "[吐]", "src": "/assets/img/icon/43.png" },
            { "alt": "[感冒]", "src": "/assets/img/icon/44.png" },
            { "alt": "[生病]", "src": "/assets/img/icon/45.png" },
            { "alt": "[拜拜]", "src": "/assets/img/icon/46.png" },
            { "alt": "[鄙视]", "src": "/assets/img/icon/47.png" },
            { "alt": "[白眼]", "src": "/assets/img/icon/48.png" },
            { "alt": "[左哼哼]", "src": "/assets/img/icon/49.png" },
            { "alt": "[右哼哼]", "src": "/assets/img/icon/50.png" },
            { "alt": "[抓狂]", "src": "/assets/img/icon/51.png" },
            { "alt": "[怒骂]", "src": "/assets/img/icon/52.png" },
            { "alt": "[打脸]", "src": "/assets/img/icon/53.png" },
            { "alt": "[顶]", "src": "/assets/img/icon/54.png" },
            { "alt": "[互粉]", "src": "/assets/img/icon/55.png" },
            { "alt": "[钱]", "src": "/assets/img/icon/56.png" },
            { "alt": "[哈欠]", "src": "/assets/img/icon/57.png" },
            { "alt": "[困]", "src": "/assets/img/icon/58.png" },
            { "alt": "[睡]", "src": "/assets/img/icon/59.png" },
            { "alt": "[吃瓜]", "src": "/assets/img/icon/60.png" },
            { "alt": "[doge]", "src": "/assets/img/icon/61.png" },
            { "alt": "[二哈]", "src": "/assets/img/icon/62.png" },
            { "alt": "[喵喵]", "src": "/assets/img/icon/63.png" },
            { "alt": "[赞]", "src": "/assets/img/icon/64.png" },
            { "alt": "[good]", "src": "/assets/img/icon/65.png" },
            { "alt": "[ok]", "src": "/assets/img/icon/66.png" },
            { "alt": "[耶]", "src": "/assets/img/icon/67.png" },
            { "alt": "[握手]", "src": "/assets/img/icon/68.png" },
            { "alt": "[作揖]", "src": "/assets/img/icon/69.png" },
            { "alt": "[来]", "src": "/assets/img/icon/70.png" },
            { "alt": "[拳头]", "src": "/assets/img/icon/71.png" },
        ]
    }
]

editor.create();
/**富文本编辑器 结束 */


// 跳转到最新消息
function GoBottom() {
    var scrollHeight = $('#chat-main').prop("scrollHeight");
    $('#chat-main').animate({ scrollTop: scrollHeight * myVue.chatData.length }, 400);
}

$('.w-e-icon-image').parent().click(function () {
    var imgInput = $('.w-e-up-img-container>div:nth-child(2)>input');
    // console.log(imgInput);
    imgInputId = '#' + imgInput[0].id;
    imgInput.removeAttr('multiple'); //禁止多选图片
})

$(document).ready(function () {
    var scrollHeight = $('#chat-main').prop("scrollHeight");
    $('#chat-main').animate({ scrollTop: scrollHeight }, 1);
})

GoBottom();